<?php
namespace app\components;

use app\components\lib\CHttpWechat;
use phpDocumentor\Reflection\Types\Self_;
use Yii;
class CTools
{



	//获取随机字符串
	public static function generateHash( $length = 8 ) {
		// 密码字符集，可任意添加你需要的字符
		$chars = "ABCDEFGHIJKLMNPQRSTUVWXYZ23456789";
		$password = "";
		for ( $i = 0; $i < $length; $i++ )
		{
			// 这里提供两种字符获取方式
			// 第一种是使用 substr 截取$chars中的任意一位字符；
			// 第二种是取字符数组 $chars 的任意元素
			// $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
			$password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
		}
		return strtolower($password);
	}

	/**
	 * 获取毫秒时间戳
	 * @return float
	 */
	public static function getMillisecond() {
		list($t1, $t2) = explode(' ', microtime());
		return (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
	}
	/**
	 * 获返回当前系统消耗内存
	 * @return float
	 */
	public static function currentMemory(){
		$size =memory_get_usage();
		$unit=array('b','kb','mb','gb','tb','pb');
		return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i];
	}

	/**
	 * 批量SQL过滤
	 *
	 * @param $val
	 * @return string
	 */
	public static function sqlFilter($val){
		return addslashes($val);
	}



	/**
	 * 写日志，方便测试（看网站需求，也可以改成把记录存入数据库）
	 * 注意：服务器需要开通fopen配置
	 * @param $word 要写入日志里的文本内容 默认值：空值
	 */
	public  static function logResult($word='',$filename ="") {
		if(empty($filename)){
			return false;
		}
		$path = Yii::$app->basePath."/logs/";
		$fp = fopen($path.$filename,"a");
		flock($fp, LOCK_EX) ;
		fwrite($fp,$word."\r\n");
		flock($fp, LOCK_UN);
		fclose($fp);
	}

	/**
	 * UUID生成
	 *
	 * @param int $pid 项目ID
	 * @param int $mid 模块ID
	 * @return string  返回长度为30字符串
	 */
	public static function generalUuid($pid = 0, $mid = 0)
	{

		$pre = "{$pid}_{$mid}_";

		return $pre . self::generateHash(30 - strlen($pre));
	}
	/**
	 * 截取domain
	 *
	 * @param string $url
	 * @return bool
	 */
	public  static function getDomain($url='') {
		$pos = strpos($url,'://');
		if($pos > 0){
			$res = explode('/',$url);
			return $res[2];
		}else{
			return false;
		}
	}

	public static function str_get_html($content)
	{
		\Yii::$classMap['HtmlFactory'] = \Yii::$app->vendorPath.'/org/simple_html_dom/HtmlFactory.php';

		$obj = new \HtmlFactory();
		return $obj->str_get_html($content);
	}

	public static function recursiveMultiArray(array $array) {
		$res = array();
		foreach (new  \RecursiveIteratorIterator(new \RecursiveArrayIterator($array)) as $key => $value) {
			$res[] = $value;
		}
		return implode("<br/>",$res);
	}

	//获取文件目录列表,该方法返回数组
	public static function getDirFiles($dir,$ext,$explodeExt ="") {
		$dirArray[]=NULL;
		if (false != ($handle = opendir ( $dir ))) {
			$i=0;
			while ( false !== ($file = readdir ( $handle )) ) {
				//去掉"“.”、“..”以及带“.xxx”后缀的文件
				if (strpos($file,$ext)) {
					if(!empty($explodeExt)){
						if(!strpos($file,$explodeExt)){
							$dirArray[$i]=$file;
							$i++;
						}
					}else{
						$dirArray[$i]=$file;
						$i++;
					}

				}
			}
			//关闭句柄
			closedir ( $handle );
		}
		return $dirArray;
	}
	public static function _transcoding($data)
	{
		if (!$data) {
			return $data;
		}
		$result = null;
		if (gettype($data) == 'unicode') {
			$result = $data;
		} elseif (gettype($data) == 'string') {
			$result = $data;
		}
		return $result;
	}
	public static function tulingGet($data = []){
		$url = "http://www.tuling123.com/openapi/api";
		$key  ="5dab137231f94b759b986c77a7afa250";
		$json = [
			'key' => $key,
			'info' => $data['info'],
			'loc' => empty($data['loc']) ? "" : $data['loc'],
			'userid' => empty($data['userid']) ? 123 : $data['userid']
		];
		$json = json_encode($json);
		$data =  CHttp::curlJson($url,$json);
//		var_dump($data);
		if($data){
			return json_decode($data,true);
		}else{
			return false;
		}


	}

	public static function json_encode($json)
	{
		return json_encode($json, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
	}

	public static function unicode_decode($name)
	{
		// 转换编码，将Unicode编码转换成可以浏览的utf-8编码
		$pattern = '/([\w]+)|(\\\u([\w]{4}))/i';
		preg_match_all($pattern, $name, $matches);
		if (!empty($matches))
		{
			$name = '';
			for ($j = 0; $j < count($matches[0]); $j++)
			{
				$str = $matches[0][$j];
				if (strpos($str, '\\u') === 0)
				{
					$code = base_convert(substr($str, 2, 2), 16, 10);
					$code2 = base_convert(substr($str, 4), 16, 10);
					$c = chr($code).chr($code2);
					$c = iconv('UCS-2', 'UTF-8', $c);
					$name .= $c;
				}
				else
				{
					$name .= $str;
				}
			}
		}
		return $name;
	}

	/**
	 * 命令行显示二维码
	 * @param $text
	 */
	public function cmdqrcode($text)
	{
		$output = new ConsoleOutput();

		$style = new OutputFormatterStyle('black', 'black');
		$output->getFormatter()->setStyle('blackc', $style);
		$style = new OutputFormatterStyle('white', 'white');
		$output->getFormatter()->setStyle('whitec', $style);
		$output->writeln("<whitec>  </whitec><blackc>  </blackc><whitec>  </whitec>");

		$pxMap[0] = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? '<whitec>mm</whitec>' : '<whitec>  </whitec>';
		$pxMap[1] = '<blackc>  </blackc>';

		$text = QRcode::text($text);

		$length = strlen($text[0]);

		$output->write("\n");
		foreach ($text as $line) {
			$output->write($pxMap[0]);
			for ($i = 0; $i < $length; $i++) {
				$type = substr($line, $i, 1);
				$output->write($pxMap[$type]);
			}
			$output->writeln($pxMap[0]);
		}
	}


	public static function br2nl($string)
	{
		return preg_replace('/\<br(\s*)?\/?\>/i', PHP_EOL, $string);
	}

	public static function robotTuling($content){
		$toolinJson = self::tulingGet(['info' => $content]);
		$content  =  $toolinJson['text'];
		if(!empty($toolinJson['url'])) $content = $content.$toolinJson['url'];

		return $content;
	}

	public static function getTimetoDate($time){
		if(is_numeric($time)){
			$value = array(
					"years" => 0, "days" => 0, "hours" => 0,
					"minutes" => 0, "seconds" => 0,
			);
			if($time >= 31556926){
				$value["years"] = floor($time/31556926);
				$time = ($time%31556926);
			}
			if($time >= 86400){
				$value["days"] = floor($time/86400);
				$time = ($time%86400);
			}
			if($time >= 3600){
				$value["hours"] = floor($time/3600);
				$time = ($time%3600);
			}
			if($time >= 60){
				$value["minutes"] = floor($time/60);
				$time = ($time%60);
			}
			$value["seconds"] = floor($time);
			//return (array) $value;
			$t=  $value["days"] ."天"." ". $value["hours"] ."小时". $value["minutes"] ."分".$value["seconds"]."秒";
			Return $t;

		}else{
			return (bool) FALSE;
		}
	}

	public static function getSearchImgMn($name){

		$start = rand(0,200);
		$url = sprintf("http://image.so.com/zj?ch=beauty&t1=625&label=美胸&listtype=hot&sn=%d&listtype=hot&temp=1",$start);
		$json = CHttp::curl($url);
		$list = json_decode($json,true);
		if(!empty($list['count'])){
			$num = $list['count'];
			$index = rand(0,$num-1);

			$info = pathinfo($list['list'][$index]['qhimg_thumb_url']);
			if(!in_array($info['extension'],['jpg','png','jpeg'])) self::getSearchImgMn($name);
			$filePath =\Yii::$app->basePath . "/runtime/wechat/img/";
			$filename = $filePath.$index.'.'.$info['extension'];
			echo $list['list'][$index]['qhimg_url'].PHP_EOL;
			$imgData = CHttpWechat::curlGet($list['list'][$index]['qhimg_url']);
			if(!$imgData)   return self::getSearchImgFile($name);;
			$res = file_put_contents($filename,$imgData);
			return  $res ? $filename : false;

		}

	}
	public static function getSearchImgDs(){
		    $filePath =\Yii::$app->basePath . "/runtime/wechat/img/money.png";
			return  $filePath;

	}

	public static function getSearchImgFile($name,$type=0){


		$str = $name;
		$json = CHttp::curl("http://image.so.com/j?q=".$str);
		$list = json_decode($json,true);
//		$data = [];
		if(!empty($list['list'])){
			$num = count($list['list']);
			$index = rand(0,$num-1);

			if(!in_array($list['list'][$index]['imgtype'],['JPEG','PNG'])) self::getSearchImgFile($name);

			$data['img'] = ($type==0 ? $list['list'][$index]['img'] : $list['list'][$index]['_thumb']);
			$data['imgtype'] =  $list['list'][$index]['imgtype'];
			$filePath =\Yii::$app->basePath . "/runtime/wechat/img/";
			if($data['imgtype'] == 'JPEG' || $data['imgtype'] == 'JPG') {
				$filename = $filePath.$index.'.jpg';
			}else{
				$filename = $filePath.$index.'.png';
			}
//			echo $data['_thumb'].PHP_EOL;
			$imgData = CHttpWechat::curlGet($data['img']);
			if(!$imgData)  return self::getSearchImgFile($name,1);
			$res = file_put_contents($filename,$imgData);

			return  $res ? $filename : false;



		}

	}

	public static function _echo($str){
		echo PHP_EOL;
		echo date("m-d H:i:s",time());
		echo " ";
		echo $str;


	}


	/**
	 * emoji表情decode
	 * @param $str
	 * @return array|mixed|stdClass
	 */
	public static function emojiDecode($str) {
		$str = json_encode($str);
		$str = preg_replace_callback('/\\\\\\\\/i', function ($str) {
			return '\\';
		}, $str);
		return json_decode($str, true);
	}


}